<template>
  <div class="homeDetail">
    <div class="tabr-nav-title">
      <van-nav-bar
        title="问题上报"
        style="width: 100%; height: 44px"
        left-arrow
        @click-left="onClickLeft"
      />
    </div>

    <div class="formList">
      <van-form  label-width="100%" label-align="top" ref="setp1FormRef">
        <van-cell-group>
          <van-field
            v-model="fromDataSetp1.facilityType"
            is-link
            readonly
            name="facilityType"
            label="设施类型"
            placeholder="点击选择设施类型"
            required
            :rules="[formRules.required]"
            @click="showPicker.facilityType = true"
          />
          <van-popup
            v-model:show="showPicker.facilityType"
            destroy-on-close
            position="bottom"
          >
            <van-picker
              :model-value="[fromDataSetp1.facilityType]"
              :columns="facilityTypeList"
              @confirm="(value) => pickerConfirm(value, 'facilityType')"
              @cancel="showPicker.facilityType = false"
            />
          </van-popup>

          <van-field
            v-model="fromDataSetp1.issueType"
            is-link
            readonly
            name="issueType"
            label="问题类型"
            placeholder="点击选择问题类型"
            required
            :rules="[formRules.required]"
            @click="showPicker.issueType = true"
          />
          <van-popup
            v-model:show="showPicker.issueType"
            destroy-on-close
            position="bottom"
          >
            <van-picker
              :model-value="[fromDataSetp1.issueType]"
              :columns="proList"
              @confirm="(value) => pickerConfirm(value, 'issueType')"
              @cancel="showPicker.issueType = false"
            />
          </van-popup>

          <van-field
            v-model="fromDataSetp1.pointId"
            is-link
            readonly
            name="pointId"
            label="涉及点位"
            placeholder="点击选择涉及点位"
            @click="showPicker.pointId = true"
          />
          <van-popup
            v-model:show="showPicker.pointId"
            destroy-on-close
            position="bottom"
          >
            <van-picker
              :model-value="[fromDataSetp1.pointId]"
              :columns="pointPickerColumns"
              @confirm="(value) => pickerConfirm(value, 'pointId')"
              @cancel="showPicker.pointId = false"
            />
          </van-popup>

          <van-field
            v-model="fromDataSetp1.isDo"
            is-link
            readonly
            name="isDo"
            label="是否现场解决"
            placeholder="点击选择是否现场解决"
            required
            :rules="[formRules.required]"
            @click="showPicker.isDo = true"
          />
          <van-popup
            v-model:show="showPicker.isDo"
            destroy-on-close
            position="bottom"
          >
            <van-picker
              :model-value="[fromDataSetp1.isDo]"
              :columns="columns"
              @confirm="(value) => pickerConfirm(value, 'isDo')"
              @cancel="showPicker.isDo = false"
            />
          </van-popup>

          <van-field
            v-model="fromDataSetp1.issueDetail"
            type="textarea"
            name="issueDetail"
            label="问题描述"
            placeholder="请输入问题描述"
          />
          
          <div class="uploadButton">
            <van-uploader
              v-model="fromDataSetp1.fileId"
              :before-read="(file) => beforeRead(file, 'url')"
              :after-read="(file) => afterRead(file, 'url')"
              :max-count="5"
            >
              <van-button type="warning" size="small"
                >上传附件</van-button
              >
            </van-uploader>
          </div>

          <template v-if="fromDataSetp1.isDo === '是'">
            <van-field
              v-model="fromDataSetp1.maintenancePersonnelNum"
              name="maintenancePersonnelNum"
              type="number"
              label="维修人员数"
              placeholder="请输入维修人员数"
              required
              :rules="[formRules.required]"
            />
            <van-field
              v-model="fromDataSetp1.usedVehicleNum"
              name="usedVehicleNum"
              type="number"
              label="使用车辆数量"
              placeholder="请输入使用车辆数量"
              required
              :rules="[formRules.required]"
            />
            <van-field
              v-model="fromDataSetp1.maintenanceCost"
              name="maintenanceCost"
              type="number"
              label="维修费用(元)"
              placeholder="请输入维修费用(元)"
              required
              :rules="[formRules.required]"
            />
            <van-field
              v-model="fromDataSetp1.maintenanceDetail"
              type="textarea"
              name="maintenanceDetail"
              label="维修过程描述"
              placeholder="请输入维修过程描述"
            />
            <div class="uploadButton">
              <van-uploader
                v-model="fromDataSetp1.beforeFileIds"
                :before-read="(file) => beforeRead(file, 'url')"
                :after-read="(file) => afterRead(file, 'url')"
                :max-count="5"
              >
                <van-button type="warning" size="small"
                  >上传维修前照片</van-button
                >
              </van-uploader>
            </div>
            <div class="uploadButton">
              <van-uploader
                v-model="fromDataSetp1.maintenanceFileIds"
                :before-read="(file) => beforeRead(file, 'url')"
                :after-read="(file) => afterRead(file, 'url')"
                :max-count="5"
              >
                <van-button type="warning" size="small"
                  >上传维修中照片</van-button
                >
              </van-uploader>
            </div>
            <div class="uploadButton">
              <van-uploader
                v-model="fromDataSetp1.afterFileIds"
                :before-read="(file) => beforeRead(file, 'url')"
                :after-read="(file) => afterRead(file, 'url')"
                :max-count="5"
              >
                <van-button type="warning" size="small"
                  >上传维修后照片</van-button
                >
              </van-uploader>
            </div>
          </template>

        </van-cell-group>
      </van-form>
    </div>
    <div class="detailFoot">
      <van-button
        style="flex: 1"
        type="primary"
        size="small"
        @click="submitClick"
        >提交问题</van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRoute } from "vue-router";
import { showSuccessToast, showToast } from "vant";
import { getPointPlus } from "@/api/index.js";
import { addPointProblem, upload } from "@/api/identification";
import formRules from "@/utils/formRules.ts";
import { facilityTypeList, problemTypeList } from "@/utils/common.ts";
import { getUserInfo } from "@/utils/userInfo.js";
const route = useRoute();
const userInfo = getUserInfo();
const proList = ref([])
const columns = [
  { text: "是", value: '1' },
  { text: "否", value: '0' }
];
const pointPickerColumns = ref([])
const setp1FormRef = ref();
const showPicker = reactive<Record<string, boolean>>({
  facilityType: false,
  issueType: false,
  isDo: false,
  pointId: false,
})

const fromDataSetp1 = reactive({
  ...route.query,
  facilityType: '',
  issueType: '',
  pointId: '',
  pointName: '',
  isDo: '',
  issueDetail: '',
  fileId: [],

  maintenancePersonnelNum: '',
  usedVehicleNum: '',
  maintenanceCost: '',
  maintenanceDetail: '',
  beforeFileIds: [],
  maintenanceFileIds: [],
  afterFileIds: [],
})

// fromDataSetp1 picker 确认
const pickerConfirm = ({ selectedOptions }, fieldName: string) => {
  showPicker[fieldName] = false;
  fromDataSetp1[fieldName]  = selectedOptions[0].text

  if (fieldName === 'facilityType') {
    proList.value = problemTypeList.filter(item => item.pid === selectedOptions[0].value)
    fromDataSetp1.issueType = ''
  }
}

// 返回布尔值
const beforeRead = (file: File | File[], type: string):boolean => {
  const files = Array.isArray(file) ? file : [file];
  const validTypes = ['image/jpeg', 'image/png'];
  for (const f of files) {
    if (!validTypes.includes(f.type)) {
      showToast("请上传 jpg/png 格式图片");
      return false;
    }
  }
  return true;
};
// 上传
const afterRead = (file: any, type: string) => {
  const formData = new FormData();
  formData.append('engine', 'MINIO')
  formData.append("file", file.file);
  file.status = "uploading";
  file.message = "上传中...";
  upload(formData).then((res: any) => {
    if (res.data.code === 200 && res.data.data) {
      file.id = res.data.data.id;
      file.status = "done";
    }
  });
};

const submitClick = async () => {
  await setp1FormRef.value.validate();

  if (fromDataSetp1.fileId.length === 0) return showToast("请上传附件")
  else if (fromDataSetp1.beforeFileIds.length === 0 && fromDataSetp1.isDo == '是') return showToast("请上传维修前照片")
  else if (fromDataSetp1.maintenanceFileIds.length === 0 && fromDataSetp1.isDo == '是') return showToast("请上传维修中照片")
  else if (fromDataSetp1.afterFileIds.length === 0 && fromDataSetp1.isDo == '是') return showToast("请上传维修后照片")

  const point = pointPickerColumns.value.find(item => item.text === fromDataSetp1.pointId) || {}
  const obj = {
    ...fromDataSetp1,
    pointId: point?.riskPointId || '',
    pointName: point?.value || '',
    facilityType: facilityTypeList.find(item => item.text === fromDataSetp1.facilityType)?.value,
    issueType: proList.value.find(item => item.text === fromDataSetp1.issueType)?.value,
    isDo: columns.find(item => item.text === fromDataSetp1.isDo)?.value,
    fileId: fromDataSetp1.fileId.map(item => item.id).join(','),
    beforeFileIds: fromDataSetp1.beforeFileIds.map(item => item.id).join(','),
    maintenanceFileIds: fromDataSetp1.maintenanceFileIds.map(item => item.id).join(','),
    afterFileIds: fromDataSetp1.afterFileIds.map(item => item.id).join(',')
  }
  addPointProblem(obj).then(res => {
    if (res.data && res.data.code === 200) {
      showSuccessToast("提交成功");
      history.back();
    } else {
      showToast("提交失败");
    }
  }).catch((err) => {
    showToast(err.message)
  });
};

const onClickLeft = () => history.back();
onMounted(() => {
  // 获取点位
  getPointPlus(userInfo.countyCode).then(res => {
    const { data } = res.data
    pointPickerColumns.value = data?.map(item => {
      return {
        text: item.name,
        value: item.name,
        riskPointId: item.id,
        address: item.address,
        coordx: item.longitude, // 经度
        coordy: item.latitude, // 纬度
      }
    })
  })
})

</script>

<style scoped lang="less">
.map-button {
  padding: var(--van-cell-vertical-padding) var(--van-cell-horizontal-padding)
}
.homeDetail {
  height: 100vh;
  background: #f7f8f7;
}

.homeHeader {
  padding: 10px;
  background: #fff;
  margin: 10px 0;
  display: flex;
  justify-content: space-between;
}

.tabr-nav-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  height: 44px;
  font-size: 18px;
  color: #29292c;
  text-align: center;
  font-style: normal;
  background: #fff;
  width: 100vw;
}
.formList {
  height: calc(100vh - 135px);
  margin: 10px 0;
  overflow-y: auto;
  background: #fff;
  .uploadButton {
    padding: 10px;
    box-sizing: border-box;
    :deep(.van-uploader) {
      width: 100%;
      .van-uploader__input-wrapper {
        width: 100%;
        .van-button {
          width: 100%;
        }
      }
    }
  }
  .newList {
    background: #fff;
    border-radius: 10px;
    padding-bottom: 1px;
    margin-bottom: 10px;
    padding: 10px;

    .list {
      width: 100%;
      background-color: rgba(242, 242, 242, 1);
      margin-bottom: 5px;
      padding: 8px 10px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      &:last-child {
        margin-bottom: 0;
      }
      .top {
        color: #333;
        width: calc(100% - 50px);
      }
      .bottom {
        margin-top: 5px;
        --van-switch-width: calc(100vw - 72px);
        position: relative;
        .tips {
          position: absolute;
          bottom: 10px;
          left: 40px;
          .tip {
            margin-left: 50px;
            font-size: 10px;
          }
        }
      }
    }
  }
}
.detailFoot {
  width: 100vw;
  padding: 20px;
  background: #fff;
  position: fixed;
  bottom: 0px;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
}
</style>
